/**
 * 
 */
package de.uni_leipzig.informatik.asv.util;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
/**
 * @author Christoph Teichmann
 * 25.04.2014
 */
public final class Encoder
{
	/**
	 * 
	 */
	private final Int2ObjectOpenHashMap<String> reverse = new Int2ObjectOpenHashMap<>();
	/**
	 * 
	 */
	private final Object2IntOpenHashMap<String> codes = new Object2IntOpenHashMap<>();
	{codes.defaultReturnValue(-1);}
	/**
	 * 
	 */
	private int number = -1;
	/**
	 * 
	 * @param codeFor
	 * @return
	 */
	public int ensure(String codeFor)
	{
		int code = get(codeFor);
		if(code < 0)
		{
			synchronized(codes)
			{
				code = get(codeFor);
				if(code < 0)
				{
					code = ++number;
					codeFor = new String(codeFor);
					reverse.put(code, codeFor);
					codes.put(codeFor, code);
				}
			}
		}
		return code;
	}
	/**
	 * 
	 * @param codeFor
	 * @return
	 */
	public int get(final String codeFor)
	{return codes.getInt(codeFor);}
	/**
	 * 
	 * @param code
	 * @return
	 */
	public String revert(final int code)
	{return reverse.get(code);}
}